using UnityEngine;
using System.Collections;

/**
 * To do all kinds of asteroid-y stuff here
 */
public class ComponentAsteroid : MonoBehaviour {
	
	public Camera FixedCamera, MainCamer;
	
	[SerializeField]
	protected float RotateMagnitude = 0.0005f;
	protected float SpeedMagnitude = 1.00f;
	protected bool FrozenFlag = false;  //set to true if gameObject is frozen
	protected int FrozenTime = 0;       //remaining time to be frozen
	protected Vector3 vBeforeFrozen;
	protected Vector3 angularVBeforeFrozen;

	// Use this for initialization
	void Start ()
	{
		// Set a random angle for it to spin around
		rigidbody.angularVelocity = Random.rotation.eulerAngles * RotateMagnitude;
		// Set a random initial velocity for it to move around
		rigidbody.velocity = Vector3.right * (Random.Range(1,10) - 5)+ Vector3.up * (Random.Range(1,10)- 5);
		
		//FixedCamera = Resources.Load("FixedCamera", typeof(Camera));
		//MainCamer = Resources.Load("MainCamera", typeof(Camera));
	}
	
	public void Frozen(int time)
	{
		FrozenFlag = true;
		FrozenTime = time;
		vBeforeFrozen = rigidbody.velocity;
		angularVBeforeFrozen = rigidbody.angularVelocity;
		rigidbody.velocity = new Vector3(0,0,0);
		rigidbody.angularVelocity = new Vector3(0,0,0);
		renderer.material.SetColor ( "_Color",Color.white );
	}
	
	void Update()
	{		

		
		if (FrozenFlag == true )
		{
			FrozenTime--;
			if ( FrozenTime == 0 )
			{
				//unfreeze
				FrozenFlag = false;
				rigidbody.velocity = vBeforeFrozen;
				rigidbody.angularVelocity = angularVBeforeFrozen;
				renderer.material.SetColor ( "_Color",Color.yellow );
			}
		}
		else
		{
			float CameraToScreen = Mathf.Abs(FixedCamera.transform.position.z-transform.position.z);
			float LeftBound = FixedCamera.ScreenToWorldPoint(new Vector3(0,0,CameraToScreen)).x;
			float RightBound = FixedCamera.ScreenToWorldPoint(new Vector3(FixedCamera.pixelWidth,FixedCamera.pixelHeight,CameraToScreen)).x;
		
			float UpperBound = FixedCamera.ScreenToWorldPoint(new Vector3(FixedCamera.pixelWidth,FixedCamera.pixelHeight,CameraToScreen)).y;
			float LowerBound = FixedCamera.ScreenToWorldPoint(new Vector3(0,0,CameraToScreen)).y;
		
			Vector3 v = rigidbody.velocity;
		
			Vector3 delta =  MainCamer.transform.position - transform.position ;
	
			v += delta.normalized/10;
		
			//Asteroid will be rebounded if they touch an edge of the screen
			if (transform.position.x <= LeftBound)
				v.x = Mathf.Abs(v.x);
			if(transform.position.x >= RightBound) 
				v.x = -Mathf.Abs(v.x);
		
			if (transform.position.y <= LowerBound)
				v.y = Mathf.Abs(v.y);	
			if(transform.position.y >= UpperBound)  
				v.y=-Mathf.Abs(v.y);
		
		
			rigidbody.velocity = v;
		}
	}
}
